package com.blog.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Api(tags="文件上传")
@RestController
public class UploadController {

    private String dirPath = "D:/file";

    @ApiImplicitParam(name = "picFile", value = "上传的文件", dataTypeClass = MultipartFile.class, required = true)
    @ApiOperationSupport(order = 10)
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public String upload(@RequestPart("picFile") MultipartFile picFile) throws IOException {
        //得到原始文件夹名
        String fileName = picFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;
        File dirFile = new File(dirPath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath = dirPath+"/"+fileName;
        picFile.transferTo(new File(filePath));
        return "/"+fileName;
    }

    @ApiImplicitParam(name = "name", value = "图片名称", example = "a.jpg",
            required = true, dataType = "string")
    @ApiOperationSupport(order = 20)
    @ApiOperation("删除文件")
    @DeleteMapping("/remove")
    public void remove(String name){
        String filePath = dirPath+name;
        new File(filePath).delete();//删除文件
    }

}
